package com.allwees.bs.task.product;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.allwees.bs.core.model.constant.CacheName;
import com.allwees.bs.module.pms.entity.Product;
import com.allwees.bs.module.pms.entity.Sku;
import com.allwees.bs.module.pms.service.PlatformProductService;
import com.allwees.bs.module.pms.service.SkuService;
import com.allwees.core.cache.RedisUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 同步sku的原价，售价，运费至spu,手动执行
 */
@Slf4j
@Service
public class SyncProductPriceTask {

    @Autowired
    private PlatformProductService platformProductService;

    @Autowired
    private SkuService skuService;

    @XxlJob(value = "syncProductPriceTask")
    public ReturnT<String> execute(String param) {
        log.info("===>同步Product Price任务");
        Page<Sku> page;
        QueryWrapper<Sku> queryWrapper = new QueryWrapper<Sku>().select("product_uuid", "retail_price", "original_price", "shipping_price").groupBy("product_uuid").having("retail_price=MIN(retail_price)");
        int pageNum = 1;
        int pageSize = 10000;
        long size;
        try {
            while(true){
                page = new Page<>(pageNum,pageSize);
                page = skuService.page(page, queryWrapper);
                size = page.getRecords().size();
                if(size == 0){
                    break;
                }
                log.info(">>>load sku from database,pageNum:{},pageSize:{},size:{}",pageNum,pageSize,size);

                List<Product> products = page.getRecords().stream().map(s -> {
                    Product product = new Product();
                    product.setUuid(s.getProductUuid());
                    product.setRetailPrice(s.getRetailPrice());
                    product.setOriginalPrice(s.getOriginalPrice());
                    product.setShippingPrice(s.getShippingPrice());
                    return product;
                }).collect(Collectors.toList());

                for (Product product : products) {
                    platformProductService.updateByUuid(product);
                    RedisUtil.del(
                            CacheName.PROD_PRODUCT_BY_UUID + "::" + product.getUuid(),
                            CacheName.PROD_PRODUCT_DETAILS + "::" + product.getUuid()
                    );
                }
                if(size < pageSize){
                    break;
                }
                pageNum ++;
            }
        } catch (Exception e) {
            log.error("syncProductPriceTask",e);
        }

        return ReturnT.SUCCESS;
    }
}
